package net.wangliping.android.tools.microblog;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import net.wangliping.android.tools.R;

public class MicroBlog extends Activity {
	
	private final String LOG_TAG = "MicroBlog";
	
	private EditText microblogContent;
	private TextView microblogLeftWords;
	private TextView microblogSendInfo;
	private Button microblogSend;
	
	private MicroBlogApi microBlogApi;
	
	private final int SETTINGS = 1;
	private final int ABOUT = 2;
	
	private final int NO_USR_PWD   = 0x01;
	private final int NO_CONTENT   = 0x02;
	private final int SEND_SUCCESS = 0x04;
	private final int SEND_FAILURE = 0x08;
	
	private String f5_username;
	private String f5_password;
	private String f5_api_key;
	private String qq_username;
	private String qq_password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.microblog_main);
        
        microblogContent = (EditText)findViewById(R.id.microblog_content);
        microblogLeftWords = (TextView)findViewById(R.id.microblog_left_words);
        microblogSendInfo = (TextView)findViewById(R.id.microblog_send_info);
        microblogSend = (Button)findViewById(R.id.microblog_send);
        
//        Properties prop = System.getProperties();
//		prop.put("proxySet", "true");
//		prop.setProperty("http.proxyHost", "172.29.8.29");
//		prop.setProperty("http.proxyPort", "80");
        
        microBlogApi= new MicroBlogApi();
        
        microblogContent.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				int leftwords = 140 - (start - before + 1);
				
				String str = getResources().getString(R.string.left_words_prefix)
						+ " " + leftwords + " "
						+ getResources().getString(R.string.left_words_tail);
				
				microblogLeftWords.setText(str);
			}
		});
        
        microblogSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				microblogSendInfo.setText(R.string.sending);
				new SendTask().execute();
//				sendMicroBlog();
			}
		});
    }
    
    private class SendTask extends AsyncTask<Object, Object, Object> {  
	    @Override
	    protected void onPostExecute(Object param) {  

	    }

	    @Override
	    protected Object doInBackground(Object... params) {
	    	sendMicroBlog();
			return null;
	    }  
	}  

    private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			handleMessageTips(msg);
		}
	};
	
	private void handleMessageTips(Message msg) {
		if (NO_USR_PWD == (msg.what & NO_USR_PWD))
			Toast.makeText(MicroBlog.this, R.string.pwd_tips, Toast.LENGTH_SHORT).show();

		if (NO_CONTENT == (msg.what & NO_CONTENT))
			Toast.makeText(MicroBlog.this, R.string.content_tips, Toast.LENGTH_SHORT).show();

		if (SEND_SUCCESS == (msg.what & SEND_SUCCESS))
			microblogSendInfo.setText(R.string.send_success);

		if (SEND_FAILURE == (msg.what & SEND_FAILURE))
			microblogSendInfo.setText(R.string.send_failure);
	}
	
	private void sendMessage(int what) {
		Message msg = mHandler.obtainMessage(what);
		mHandler.sendMessage(msg);
	}
	
    private void sendMicroBlog() {
    	String content = microblogContent.getText().toString();
    	
    	if (TextUtils.isEmpty(content)) {
    		sendMessage(NO_CONTENT | SEND_FAILURE);
    		return;
    	}
    	
    	MicroBlogData usr = new MicroBlogData(this);
		HashMap<String, String> map = usr.getUserValues(MicroBlogData.SITE_F5);
		if (map != null && map.size() != 0) {
			f5_username = map.get(MicroBlogData.COL_USER);
			f5_password = map.get(MicroBlogData.COL_PWD);
			f5_api_key  = map.get(MicroBlogData.COL_API_KEY);
		}

		if (map != null && map.size() != 0) {
			map = usr.getUserValues(MicroBlogData.SITE_QQ);
			qq_username = map.get(MicroBlogData.COL_USER);
			qq_password = map.get(MicroBlogData.COL_PWD);
		}
		
		usr.close();
		
		boolean f5 = false;
		boolean qq = false;
		
		if (!TextUtils.isEmpty(f5_username) && !TextUtils.isEmpty(f5_password)) {
			f5 = true;
			Log.d(LOG_TAG, "Prepare to send follow5");
			microBlogApi.updateF5(f5_username, f5_password, content, f5_api_key);
		}
		
		if (!TextUtils.isEmpty(qq_username) && !TextUtils.isEmpty(qq_password)) {
			qq = true;
			Log.d(LOG_TAG, "Prepare to send QQ");
			microBlogApi.updateQQ(qq_username, qq_password, content);
		}
		
		if (!f5 && !qq) {
			sendMessage(SEND_FAILURE);
		} else {
			sendMessage(SEND_SUCCESS);
		}
    }
    
    private void gotoActivity(Class<?> cls) {
    	Intent intent = new Intent();  
    	intent.setClass(MicroBlog.this, cls);  
    	startActivity(intent);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, SETTINGS, 0, R.string.settings).setIcon(
				android.R.drawable.ic_menu_preferences);
		menu.add(0, ABOUT, 0, R.string.about).setIcon(
				android.R.drawable.ic_menu_help);
        return true;

    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case SETTINGS:
        	gotoActivity(Settings.class);
            return true;
        case ABOUT:
        	createDialog().show();
            return true;
        }
        return false;
    }
    
	private Dialog createDialog() {
		return new AlertDialog.Builder(MicroBlog.this).setTitle(R.string.about)
				.setMessage(R.string.about_message)
				.setPositiveButton(R.string.settings_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						}).create();
	}
}